﻿using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Design;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using TouchSocket.Core;
using TouchSocket.Sockets;

namespace TouchSocket_TCP的使用
{
    public partial class FrmClient : UIForm
    {
        public FrmClient()
        {
            InitializeComponent();

            this.btn_DisConnectServer.Enabled = false;
        }

        private TcpClient tcpClient;
        private bool isConneted = false;

        private async Task<bool> ConnectServer(string ip, string port)
        {
            tcpClient = new TcpClient();
            tcpClient.Connecting = (client, e) =>
            {

                this.Invoke(() =>
                {
                    this.txt_ClientRev.AppendText($"正在连接服务器{ip}:{port}...{Environment.NewLine}");
                });
                return EasyTask.CompletedTask;

            };//即将连接到服务器，此时已经创建socket，但是还未建立tcp

            tcpClient.Connected = (client, e) =>
            {
                this.Invoke(() =>
                {
                    this.txt_ClientRev.AppendText($"成功连接到服务器{ip}:{port}...{Environment.NewLine}");
                    isConneted = true;
                });
                return EasyTask.CompletedTask;
            };//成功连接到服务器

            tcpClient.Closing = (client, e) =>
            {
                this.Invoke(() =>
                {
                    this.txt_ClientRev.AppendText($"正在与服务器{ip}:{port}断开连接...{Environment.NewLine}");
                });
                return EasyTask.CompletedTask;
            };//即将从服务器断开连接。此处仅主动断开才有效。

            tcpClient.Closed = (client, e) =>
            {

                this.Invoke(() =>
                {
                    this.txt_ClientRev.AppendText($"与服务器{ip}:{port}断开连接！{Environment.NewLine}");
                    isConneted = false;
                });
                return EasyTask.CompletedTask;
            };//从服务器断开连接，当连接不成功时不会触发。

            tcpClient.Received = (client, e) =>
            {
                //从服务器收到信息。但是一般byteBlock和requestInfo会根据适配器呈现不同的值。
                var mes = e.ByteBlock.Span.ToString(Encoding.UTF8);

                this.Invoke(() =>
                {
                    this.txt_ClientRev.AppendText($"接收服务器{ip}:{port}信息=>{mes}{Environment.NewLine}");
                });
                return EasyTask.CompletedTask;
            };

            //载入配置
            await tcpClient.SetupAsync(new TouchSocketConfig()
                  .SetRemoteIPHost($"{ip}:{port}")

                  .ConfigureContainer(a =>
                  {
                      a.AddConsoleLogger();//添加一个日志注入

                  })
                  .ConfigurePlugins(a =>
                  {
                      // 断线重连5次,每次间隔5秒
                      a.UseTcpReconnection().SetConnectAction(5, false, 5000);
                  }));

            await tcpClient.ConnectAsync();//调用连接，当连接不成功时，会抛出异常。

            Result result = await tcpClient.TryConnectAsync();//或者可以调用TryConnectAsync
            if (!result.IsSuccess)
            {
                return false;
            }
            return true;


        }

        /// <summary>
        /// 连接到服务器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void btn_ConnectServer_Click(object sender, EventArgs e)
        {
            //获取IP和端口
            string ip = txt_ServerIP.Text.Trim();
            string port = txt_ServerPort.Text.Trim();
            //校验处理
            if (!ip.IsIP4())
            {
                UIMessageTip.ShowWarning("请输入正确的IP地址！");
                return;
            }
            if (!port.IsInt())
            {
                UIMessageTip.ShowWarning("请输入正确的端口号！");
                return;
            }
            bool isConnnect = await ConnectServer(ip, port);
            if (isConnnect)
            {
                UIMessageTip.ShowOk("连接成功！");
                this.btn_ConnectServer.Enabled = false;
                this.btn_DisConnectServer.Enabled = true;
            }
        }
        /// <summary>
        /// 断开连接
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_DisConnectServer_Click(object sender, EventArgs e)
        {
            //关闭连接 判断是否连接上了
            if (tcpClient != null && isConneted)
            {
                tcpClient.Close();
                UIMessageTip.ShowOk("断开连接成功！");
                this.btn_ConnectServer.Enabled = true;
            }
            else
            {
                UIMessageTip.ShowWarning("尚未连接到服务器！");
            }
        }
        /// <summary>
        /// 发送信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_ClientSend_Click(object sender, EventArgs e)
        {
            //校验处理
            if (tcpClient == null || !isConneted)
            {
                UIMessageTip.ShowWarning("尚未连接到服务器！");
            }

            string msg = this.txt_CilentSend.Text.Trim();
            if (string.IsNullOrEmpty(msg))
            {
                UIMessageTip.ShowWarning("请输入要发送的信息！");
                return;
            }

            //发送信息
            tcpClient.SendAsync(Encoding.UTF8.GetBytes(msg));


        }
    }
}
